package com.globallogic.dailyplanner.ejb;

import javax.ejb.MessageDriven;
import javax.interceptor.Interceptors;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;

import com.globallogic.dailyplanner.dto.History;
import com.globallogic.dailyplanner.dto.Mail;
import com.globallogic.dailyplanner.dto.MailStatusEnum;
import com.globallogic.dailyplanner.dto.User;
import com.globallogic.dailyplanner.service.HistoryService;
import com.globallogic.dailyplanner.service.MailService;
import com.globallogic.dailyplanner.service.UserService;
import com.globallogic.dailyplanner.vo.JMSAnswerMessageVO;

@MessageDriven(mappedName="jms/DailyPlannerAswerQueue")
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class MailStatusCheckerBean implements MessageListener{
	@Autowired
	private HistoryService historyService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MailService mailService;

	@Override
	public void onMessage(Message jmsMessage) {
		ObjectMessage jmsObjectMessage = (ObjectMessage)jmsMessage;
		try {
			JMSAnswerMessageVO answer = (JMSAnswerMessageVO)jmsObjectMessage.getObject();
			addToHistory(answer.getUserEmail(), answer.getMailId(), answer.getStatusEnum());
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	//TODO move to service layer
	private void addToHistory(String email, int mailId, MailStatusEnum status) {
		User user = userService.getByEmail(email);
		Mail mail = mailService.getById(mailId);
		
		History history = new History();
		history.setMail(mail);
		history.setUser(user);
		history.setStatus(status);
		
		historyService.save(history);
	}

}
